package com.chaosj.skill.discovery.loadbalance

import com.chaosj.skill.spi.seata.LoadLevel

import java.util.concurrent.atomic.AtomicInteger

/**
 * @Description:
 * @author: caoyangjie
 * @date: 2019年12月2019/12/23日 17:25
 * @Copyright: © 赢时胜
 */
@LoadLevel(name="RoundRobinLoadBalance")
class RoundRobinLoadBalance extends AbstractLoadBalance{
    private final AtomicInteger sequence = new AtomicInteger()

    @Override
    <T> T doSelect(List<T> invokers) {
        int length = invokers.size()
        return invokers.get(getPositiveSequence() % length)
    }

    private int getPositiveSequence() {
        for (; ; ) {
            int current = sequence.get()
            int next = current >= Integer.MAX_VALUE ? 0 : current + 1
            if (sequence.compareAndSet(current, next)) {
                return current
            }
        }
    }
}
